package me.znext.learn.android.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

import java.util.HashMap;

public class UserDAO {
  private DBHelper helper;
  private SQLiteDatabase db;// 创建SQLiteDatabase对象

  public UserDAO(Context context) {
    helper = new DBHelper(context);
  }

  public boolean signUp(String uname, String pw) {
    db = helper.getWritableDatabase();
    try { // 有可能出现用户名重复
      db.execSQL("INSERT INTO user (uname, pw) values (?,?)", new String[]{uname, pw});
    } catch (SQLiteException ignored) {
      return false;
    }
    return true;
  }

  public boolean signIn(String uname, String pw) {
    db = helper.getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT 1 FROM user WHERE uname = ? AND pw = ? LIMIT 1", new String[]{uname, pw});
    boolean isValid = cursor.getCount() == 1;
    cursor.close();
    return isValid;
  }

  public HashMap<String, String> getProfile (String uname) {
    db = helper.getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM user WHERE uname = ? LIMIT 1", new String[]{uname});
    cursor.moveToNext();
    HashMap<String, String> profile = new HashMap<>();
    profile.put("sex", cursor.getString(cursor.getColumnIndex("sex")));
    profile.put("birthday", cursor.getString(cursor.getColumnIndex("birthday")));
    cursor.close();
    return profile;
  }

  public void update(String uname, String field, String value) {
    db = helper.getWritableDatabase();
    db.execSQL("UPDATE user SET "+ field + " = ? WHERE uname = ?", new String[]{value, uname});
  }
}
